package com.example.seakdreamandroid;

import static com.example.seakdreamandroid.Constant.BASE_URL;
import static com.mob.MobSDK.getContext;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.example.seakdreamandroid.entity.User;
import com.example.seakdreamandroid.firstPage.MyBannerAdapter;
import com.example.seakdreamandroid.lottery.Lottery;
import com.example.seakdreamandroid.questions.Questions;
import com.example.seakdreamandroid.sleep.AlarmClockAndPrompt;
import com.example.seakdreamandroid.sleep.AlarmItemDetail;
import com.example.seakdreamandroid.sleep.StartSleep;
import com.example.seakdreamandroid.sleep.entity.ClockInfo;
import com.google.android.material.card.MaterialCardView;
import com.youth.banner.Banner;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.listener.OnPageChangeListener;
import com.youth.banner.transformer.ZoomOutPageTransformer;

import org.json.JSONObject;

import java.io.IOException;
import java.io.Serializable;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MemberActivity extends AppCompatActivity implements PayDetailFragment.stateListener {

    private Banner banner;
    //轮播图的适配器
    private MyBannerAdapter bannerAdapter;
    private MaterialCardView materialCardView1;
    private MaterialCardView materialCardView2;
    private MaterialCardView materialCardView3;
    private MaterialCardView materialCardView4;
    private PayDetailFragment fragment;
    private TextView vipEndTime;
    User user;
    private String str = "";
    private FormBody body;
    private ImageView headshot;
    private TextView nickname;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_member);
        banner = findViewById(R.id.authority_banner);
        initBanner();
        initCard();
        ImageView back = findViewById(R.id.img_btn_return_sleep);
        vipEndTime = findViewById(R.id.vip_endTime);
        setVipEndTime();
        setUser();
        user = (User) getApplication();
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        nickname = findViewById(R.id.username1);
        headshot = findViewById(R.id.headshot1);
    }
    public void setVipEndTime(){
        String userId = user.getUserId();
        Request request = new Request.Builder()
                //设置请求的地址，默认的请求方式是Get请求
                .url(BASE_URL+"UserInfo/getUserInfo"+"?id="+userId)
                //创建Request对象
                .build();
        //3.发送请求，获取响应
        OkHttpClient okHttpClient = new OkHttpClient();
        Call call = okHttpClient.newCall(request);
        //发起异步的请求，不需要手动创建子线程
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //请求失败时回调
                Log.e("MineActivity","onFailure，请求数据失败");
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MemberActivity.this,"网络故障，请检查网络",Toast.LENGTH_LONG).show();

                    }
                });
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {

                //请求成功时回调
                Log.i("MineActivity","onResponse"+"成功");
                try {
                    String resultStr = response.body().string();
                    JSONObject object = new JSONObject(resultStr);
                    JSONObject data = object.getJSONObject("data");
                    String dateStr = data.getString("vipEndTime"); //output is 2014-01-01T21:13:00.000Z
                    Log.e("66",dateStr);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSS");
                    Date endDate = sdf.parse(dateStr);
                    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
                    String endDate2 = sdf2.format(endDate);
                    String ifVip = data.getString("ifVip");
                    Log.e("66",endDate.toString());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (ifVip.equals("1")){
                                    vipEndTime.setText(endDate2);
                                }else {
                                    vipEndTime.setText("您还不是Vip，请充值");
                                }
                            }
                        });
                }catch (Exception e){
                    e.printStackTrace();
                }
                //setview
            }
        });

    }

    private void initBanner() {
        banner.addPageTransformer(new ZoomOutPageTransformer());
        List<String> imageUrls = getBannerData();
        bannerAdapter = new MyBannerAdapter(imageUrls,this);
        banner.addBannerLifecycleObserver(this)
                .setAdapter(bannerAdapter)
                .setIndicator(new CircleIndicator(this));
        //设置指示器必须在条件指示器之后
        banner.setIndicatorSpace(20);
        banner.setIndicatorWidth(20,20);
        banner.setIndicatorHeight(20);
    }

    //获取网络轮播图的信息
    private List<String> getBannerData(){
        List<String> result = new ArrayList<String>();
        //模拟从服务器获取轮播图的图片的url，起始还应该包括点击时候的处理方法等等，此处暂且忽略，到时候再改
        result.add("https://link.jscdn.cn/1drv/aHR0cHM6Ly8xZHJ2Lm1zL2kvcyFBbW55X3RpQjQ0N19oQkhaRzVERkdRaUsxZEpfP2U9YlprTVc3.jpg");
        result.add("https://link.jscdn.cn/1drv/aHR0cHM6Ly8xZHJ2Lm1zL2kvcyFBbW55X3RpQjQ0N19oQkx5Z2otV2RhQnprZDBlP2U9NW1qOWZv.jpg");
        result.add("https://link.jscdn.cn/1drv/aHR0cHM6Ly8xZHJ2Lm1zL2kvcyFBbW55X3RpQjQ0N19oQk1aV3VQR0hLdHBDeElMP2U9b3VTd2du.jpg");
        result.add("https://link.jscdn.cn/1drv/aHR0cHM6Ly8xZHJ2Lm1zL2kvcyFBbW55X3RpQjQ0N19oQlJ2cHZtNXFyX1VQQmx5P2U9Zm93ajM3.jpg");
        return result;
    }
    private void initCard(){
        materialCardView1=findViewById(R.id.mcv_1);
        materialCardView2=findViewById(R.id.mcv_2);
        materialCardView3=findViewById(R.id.mcv_3);
        materialCardView4=findViewById(R.id.mcv_4);
        user = (User) getApplication();
        materialCardView1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                fragment=new PayDetailFragment();
                fragment.setStateListener(MemberActivity.this);
                fragment.show(getSupportFragmentManager(),"payDetailFragment");
                Bundle bundle = new Bundle();
                bundle.putString("Data", "198.00");
                fragment.setArguments(bundle);

            }
        });
        materialCardView2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                fragment=new PayDetailFragment();
                fragment.setStateListener(MemberActivity.this);
                fragment.show(getSupportFragmentManager(),"payDetailFragment");
                Bundle bundle = new Bundle();
                bundle.putString("Data", "128.00");
                fragment.setArguments(bundle);
            }
        });
        materialCardView3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                fragment=new PayDetailFragment();
                fragment.setStateListener(MemberActivity.this);
                fragment.show(getSupportFragmentManager(),"payDetailFragment");
                Bundle bundle = new Bundle();
                bundle.putString("Data", "88.00");
                fragment.setArguments(bundle);

            }
        });
        materialCardView4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                fragment=new PayDetailFragment();
                fragment.setStateListener(MemberActivity.this);
                fragment.show(getSupportFragmentManager(),"payDetailFragment");
                Bundle bundle = new Bundle();
                bundle.putString("Data", "30.00");
                fragment.setArguments(bundle);

            }
        });
    }

    @Override
    public void close(String s, String state) {
        if (state.equals("支付成功")) {
            str ="?";

            user.setIf_vip("1");

            switch (s.split("\\.")[0]){
                case "30":
                    user.setVipTime("30");
                    break;
                case "88":
                    user.setVipTime("90");
                    break;
                case "128":
                    user.setVipTime("180");
                    break;
                case "198":
                    user.setVipTime("365");
                    break;
            }
            Log.e("viptime",user.getVipTime());
            body = new FormBody.Builder()
                    .add("userId",user.getUserId())
                    .add("vipTime",user.getVipTime())
                    .build();
            postAsync(str,body);
        }else{
            Toast.makeText(MemberActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
        }
        fragment.dismiss();


    }

    /**
     * 修改数据中会员状态
     * @param s
     * @param body
     */
    private void postAsync(String s, FormBody body) {
        OkHttpClient okHttpClient = new OkHttpClient();
        //创建请求对象（Request）
        Request request = new Request.Builder()
                //设置
                .url(Constant.BASE_URL+"UserInfo/openVip")
                .post(body)//设置请求方式为post，添加了请求体
                //创建Request对象
                .build();
        //发送请求，获取响应
        //(一个call对象对应一个response)
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okHttp","onfilure");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //修改用户界面，需要使用Handler或RunOnUiThread
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MemberActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        setVipEndTime();
                        setUser();
                    }
                });
            }
        });

    }


    public void setUser(){
        String userId = user.getUserId();
        Request request = new Request.Builder()
                //设置请求的地址，默认的请求方式是Get请求
                .url(BASE_URL+"UserInfo/getUserInfo"+"?id="+userId)
                //创建Request对象
                .build();
        //3.发送请求，获取响应
        OkHttpClient okHttpClient = new OkHttpClient();
        Call call = okHttpClient.newCall(request);
        //发起异步的请求，不需要手动创建子线程
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //请求失败时回调
                Log.e("MineActivity","onFailure，请求数据失败");
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MemberActivity.this,"网络故障，请检查网络",Toast.LENGTH_LONG).show();

                    }
                });
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功时回调
                Log.i("MineActivity","onResponse"+"成功");
                try {
                    String resultStr = response.body().string();
                    JSONObject object = new JSONObject(resultStr);
                    JSONObject data = object.getJSONObject("data");
                    if(!data.isNull("headshot")){
                        String headshot1 = data.getString("headshot");
                        byte[] bs = Base64.decode(headshot1, Base64.DEFAULT);
                        for (int i = 0; i < bs.length; ++i) {
                            if (bs[i] < 0) {
                                bs[i] += 256;
                            }
                        }
                        Bitmap bitmap = BitmapFactory.decodeByteArray(bs,0,bs.length);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Glide.with(MemberActivity.this).load(bitmap).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(headshot);
                            }
                        });
                    }
                    if(!data.isNull("userName")){
                        String if_vip = data.getString("ifVip");
                        String nickname1 = data.getString("userName");
                       runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (if_vip.equals("1")){
                                    nickname.setText(nickname1+"(会员)");
                                    nickname.setTextColor(Color.RED);
                                }else {
                                    nickname.setText(nickname1);
                                    nickname.setTextColor(Color.BLACK);
                                }

                            }
                        });
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                //setview
            }
        });

    }
}